import React, { Component } from 'react';
import { Switch, Space, Form } from "antd"
import TheTable from "../../../components/TheTable";
import TheButton from "../../../components/TheButton";
import TheDialog from "../../../components/TheDialog";
import TheUpload from '../../../components/TheUpload';
import '../style/index.less'
import { apiGetShufflingPage, apiGetShufflingAdd, apiGetShufflingEdit, apiGetShufflingDel, apiUpdateStatusBySite } from '@/request/configuration'
import TheImage from "../../../components/TheImage";
// import Editor from "../component/editor";
import Editor from "./component/editor";
import ThePagination from "@/components/ThePagination";

class Shuffling extends Component {
  state = {
    loading: false,
    dataSource: null,
    activeDataSource: [],
    category: '',
    columnsCarouse: [
      {
        title: "图片",
        dataIndex: "configCarouselFilez",
        key: "configCarouselFilez",
        render: (text, record) => {
          return <TheImage width={270} height={106} src={record.configCarouselFilez} />
        }
      },
      {
        title: "标题",
        dataIndex: "configCarouselTitle",
        key: "configCarouselTitle"
      },
      {
        title: "排序",
        dataIndex: "configCarouselSort",
        key: "configCarouselSort"
      },
      {
        title: "操作",
        render: (text, record) => {
          let category = ''
          switch (record.configCarouselSite) {
            case 1:
              category = 'carousel'
              break;
            case 2:
              category = 'active'
              break;
            case 8:
              category = 'card'
              break;
            default:
              break;
          }
          return <>
            <TheButton haspermi={['set:shuffling:carouseEdit']} onClick={() => this.openDialog('editor', category, record)}>修改</TheButton>
            <TheButton haspermi={['set:shuffling:carouseDelete']} onClick={() => this.del(record)}>删除</TheButton>
          </>
        }
      },
    ],
    columnsActive: [
      {
        title: "图片",
        dataIndex: "configCarouselFilez",
        key: "configCarouselFilez",
        render: (text, record) => {
          return <TheImage width={270} height={106} src={record.configCarouselFilez} />
        }
      },
      {
        title: "标题",
        dataIndex: "configCarouselTitle",
        key: "configCarouselTitle"
      },
      {
        title: "排序",
        dataIndex: "configCarouselSort",
        key: "configCarouselSort"
      },
      {
        title: "操作",
        render: (text, record) => {
          return <>
            <TheButton haspermi={['set:shuffling:activeEdit']} onClick={() => this.openDialog('editor', 'cardCross', record)}>修改</TheButton>
            {/* <TheButton haspermi={['set:shuffling:activeDelete']} onClick={() => this.del(record)}>删除</TheButton> */}
          </>
        }
      },
    ],
    dialogStatus: false,
    title: '',
    radioValue: '',
    initialValues: null,
    btnLoading: false,
    activeLoading: false,
    edit: false,
    type: "",
    total: 0,
    pageParams: {
      pageNo: 1,
      pageSize: 3,
    },
    pageActive: {
      pageNo: 1,
      pageSize: 3,
    },
    pageCard: {
      pageNo: 1,
      pageSize: 3,
    },
    cardDataSource: [],
    cardSource: [],
    activetotal: 0,
    Cardtotal: 0,
    cardloading: true,
    cardSwitch: false,
    backgroundSwitch: false,
    topbg: [],
    middlebg: [],
    bottombg: [],
    topdata: [],
    middledata: [],
    bottomdata: []
  }
  async componentDidMount() {
    let { pageNo, pageSize } = this.state.pageParams
    await this.getActiveData(pageNo, pageSize)
    await this.getHomeBannerData(pageNo, pageSize)
    await this.getCardAdsData()
    await this.getCardBannerData(pageNo, pageSize)
    await this.getTopBackgroundData()
    await this.getMiddleBackgroundData()
    await this.getBottomBackgroundData()
  }
  getActiveData = async (pageNo, pageSize) => {
    const response = await apiGetShufflingPage({ configCarouselSite: '2', pageNo, pageSize })
    if (response.code === 0) {
      this.setState({
        activeDataSource: response.data,
        activeLoading: false,
        activetotal: response.totalCount,
        pageActive: {
          pageActiveNo: pageNo,
          pageActiveSize: pageSize
        }
      })
    } else {
      this.setState({
        activeDataSource: [],
        activeLoading: false
      })
    }
  }
  getHomeBannerData = async (pageNo, pageSize) => {
    const bannerHome = await apiGetShufflingPage({ configCarouselSite: '1', pageNo, pageSize })
    if (bannerHome.code === 0) {
      this.setState({
        dataSource: bannerHome.data,
        loading: false,
        total: bannerHome.totalCount,
        pageParams: {
          pageNo,
          pageSize
        }
      })
    } else {
      this.setState({
        dataSource: null,
        loading: false
      })
    }
  }
  getCardBannerData = async (pageNo, pageSize) => {
    const cardBanner = await apiGetShufflingPage({ configCarouselSite: '8', configSiteType: '1', pageNo, pageSize })
    if (cardBanner.code === 0) {
      if (cardBanner.data.length !== 0 && cardBanner.data[0].configCarouselStatus === 'Y') {
        this.setState({
          cardSwitch: true
        })
      }
      this.setState({
        cardDataSource: cardBanner.data,
        cardloading: false,
        Cardtotal: cardBanner.totalCount,
        pageCard: {
          pageCardNo: pageNo,
          pageCardSize: pageSize
        }
      })
    } else {
      this.setState({
        cardDataSource: null,
        cardloading: false
      })
    }
  }
  getCardAdsData = async () => {
    const cardAds = await apiGetShufflingPage({ configCarouselSite: '8', configSiteType: '2', pageNo: 1, pageSize: 2 })
    if (cardAds.code === 0) {
      this.setState({
        cardSource: cardAds.data,
        loading: false,
        // total: cardAds.totalCount,
      })
    } else {
      this.setState({
        cardSource: null,
        loading: false
      })
    }
  }
  getTopBackgroundData = async () => {
    const topbg = await apiGetShufflingPage({ configCarouselSite: '9', configSiteType: '3', pageNo: 1, pageSize: 1 })
    if (topbg.code === 0 && topbg.data.length !== 0) {
      if (topbg.data.length !== 0 && topbg.data[0].configCarouselStatus === 'Y') {
        this.setState({
          backgroundSwitch: true
        })
      }
      this.setState({
        topId: topbg.data[0].configCarouselId,
        topbg: topbg.data[0].configCarouselFilez ? [{
          name: 'image',
          uid: topbg.data[0].configCarouselId,
          url: topbg.data[0].configCarouselFilez,
          status: 'done'
        }] : [],
        topdata: topbg.data
      }, () => {
        console.log(this.state.topbg);
      })
    } else {
      this.setState({
        topbg: [],
      })
    }
  }
  getMiddleBackgroundData = async () => {
    const middlebg = await apiGetShufflingPage({ configCarouselSite: '9', configSiteType: '4', pageNo: 1, pageSize: 1 })
    if (middlebg.code === 0 && middlebg.data.length !== 0) {
      this.setState({
        middleId: middlebg.data[0].configCarouselId,
        middlebg: middlebg.data[0].configCarouselFilez ? [{
          name: 'image',
          uid: middlebg.data[0].configCarouselId,
          url: middlebg.data[0].configCarouselFilez,
          status: 'done'
        }] : [],
        middledata: middlebg.data
      })
    } else {
      this.setState({
        middlebg: [],
      })
    }
  }
  getBottomBackgroundData = async () => {
    const bottombg = await apiGetShufflingPage({ configCarouselSite: '9', configSiteType: '5', pageNo: 1, pageSize: 1 })
    if (bottombg.code === 0 && bottombg.data.length !== 0) {
      this.setState({
        bottomId: bottombg.data[0].configCarouselId,
        bottombg: bottombg.data[0].configCarouselFilez ? [{
          name: 'image',
          uid: bottombg.data[0].configCarouselId,
          url: bottombg.data[0].configCarouselFilez,
          status: 'done'
        }] : [],
        bottomdata: bottombg.data
      })
    } else {
      this.setState({
        bottombg: [],
      })
    }
  }

  update = value => {
    this.setState({
      dialogStatus: true,
      title: '修改轮播图',
      initialValues: value,
      radioValue: value.configCarouselType,
      edit: true
    })
  }

  del = record => {
    React.$confirm({
      title: "警告",
      content: `确定删除此信息吗？`,
      onOk: async () => {
        this.setState({
          loading: true,
        })
        const data = await apiGetShufflingDel({ configCarouselId: record.configCarouselId })
        if (data.code === 0) {
          await this.getCardBannerData(1, 3)
          await this.getHomeBannerData(1, 3)
          await this.getActiveData(1, 3)
          this.setState({
            loading: false
          })
        } else {
          this.setState({
            loading: false
          })
        }
      }
    });
  }
  openDialog = (type, category, value, couponId) => {
    let title = ''
    switch (category) {
      case 'carousel':
        title = 'Banner轮播图'
        break;
      case 'active':
        title = '横通广告位'
        break;
      case 'card':
        title = '卡片轮播图'
        break;
      case 'cardCross':
        title = '卡片广告位'
        break;
      default:
        break;
    }
    if (type === "editor") {

      this.setState({ title: "修改" + title, dialogStatus: true, initialValues: value, couponId, type: 'editor', edit: true, category });
    } else {

      this.setState({ title: "新增" + title, dialogStatus: true, initialValues: null, type: 'add', category });
    }
  }
  dialogCancel = () => {
    this.setState({
      dialogStatus: false,
      title: '',
      btnLoading: false,
      initialValues: null,
      edit: false
    })
  }
  onFinish = async values => {
    const { edit, initialValues, category } = this.state
    this.setState({
      btnLoading: true
    })
    let data = null
    let configCarouselSite = ''
    let configSiteType = ''
    switch (category) {
      case 'carousel':
        configCarouselSite = '1'
        break;
      case 'active':
        configCarouselSite = '2'
        break;
      case 'card':
        configCarouselSite = '8'
        configSiteType = '1'
        break;
      case 'cardCross':
        configCarouselSite = '8'
        configSiteType = '2'
        break;
      default:
        break;
    }
    if (edit) {
      data = await apiGetShufflingEdit({ ...values, configCarouselId: initialValues.configCarouselId, configCarouselSite, configSiteType })
    } else {
      data = await apiGetShufflingAdd({ ...values, configCarouselSite, configSiteType })
    }
    if (data.code === 0) {
      this.setState({
        pageParams: {
          pageNo: 1,
          pageSize: 3
        }
      })
      await this.dialogCancel()
      await this.getActiveData(1, 3)
      await this.getHomeBannerData(1, 3)
      await this.getCardAdsData()
      await this.getCardBannerData(1, 3)
      if (initialValues) {
        React.$message({
          type: 'info',
          content: '修改成功'
        })
      } else {
        React.$message({
          type: 'info',
          content: '新增成功'
        })
      }
    } else {
      this.setState({
        btnLoading: false
      })
    }
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageParams: {
        pageNo,
        pageSize
      }
    })
    this.getHomeBannerData(pageNo, pageSize)
  }
  pageActiveChange = (pageNo, pageSize) => {
    this.setState({
      pageActive: {
        pageActiveNo: pageNo,
        pageActiveSize: pageSize
      }
    })
    this.getActiveData(pageNo, pageSize)
  }
  pageCardChange = (pageNo, pageSize) => {
    this.setState({
      pageCard: {
        pageCardNo: pageNo,
        pageCardSize: pageSize
      }
    })
    this.getCardBannerData(pageNo, pageSize)
  }
  bannerOnChange = async (e) => {
    const { cardDataSource, cardSource } = this.state
    if (cardDataSource.length !== 0 && cardSource.length !== 0) {
      let status = 'N'
      if (e) {
        status = 'Y'
      }
      let res = await apiUpdateStatusBySite({ configCarouselSite: '8', configCarouselStatus: status })
      if (res.code === 0) {
        React.$message({
          type: 'info',
          content: status === 'Y' ? '卡片轮播、广告位开启成功！' : '卡片轮播、广告位关闭成功！'
        })
        this.setState({
          cardSwitch: e
        })
      }
    } else {
      React.$message({
        type: 'warning',
        content: '无卡片轮播、广告数据不可开启！'
      })
    }
  }
  backGroundOnSwitch = async (e) => {
    let status = 'N'
    if (e) {
      status = 'Y'
    }
    let res = await apiUpdateStatusBySite({ configCarouselSite: '9', configCarouselStatus: status })
    if (res.code === 0) {
      React.$message({
        type: 'info',
        content: status === 'Y' ? '背景氛围图开启成功！' : '背景氛围图关闭成功！'
      })
      this.setState({
        backgroundSwitch: e
      })
    }
  }
  getTopFileResult = async (data) => {
    let configCarouselId = this.state.topId ?? ""
    if (data.length > 0 && data[0].hasOwnProperty('response')&& data[0].response) {
      let str = data[0].response.data
      if (!configCarouselId) {
        await apiGetShufflingAdd({ configCarouselFilez: str, configCarouselSite: '9', configSiteType: '3', configCarouselType: '0', configCarouselTitle: '顶部背景图', configCarouselSort: '1' })
      } else {
        await apiGetShufflingEdit({ configCarouselId, configCarouselFilez: str, configCarouselSite: '9', configSiteType: '3', configCarouselType: '0', configCarouselTitle: '顶部背景图', configCarouselSort: '1' })
      }
    }
  }





  getMiddleFileResult = async (data) => {

    let configCarouselId = this.state.middleId ?? ""
    if (data.length > 0 && data[0].hasOwnProperty('response')&& data[0].response) {
      let str = data[0].response.data
      if (!configCarouselId) {
        await apiGetShufflingAdd({ configCarouselFilez: str, configCarouselSite: '9', configSiteType: '4', configCarouselType: '0', configCarouselTitle: '中部背景图', configCarouselSort: '1' })

      } else {
        await apiGetShufflingEdit({ configCarouselId, configCarouselFilez: str, configCarouselSite: '9', configSiteType: '4', configCarouselType: '0', configCarouselTitle: '中部背景图', configCarouselSort: '1' })

      }
    }
  }
  getBottomFileResult = async (data) => {
    let configCarouselId = this.state.bottomId ?? ""
    if (data.length > 0 && data[0].hasOwnProperty('response')&& data[0].response) {
      let str = data[0].response.data
      if (!configCarouselId) {
        await apiGetShufflingAdd({ configCarouselFilez: str, configCarouselSite: '9', configSiteType: '5', configCarouselType: '0', configCarouselTitle: '底部背景图', configCarouselSort: '1' })

      } else {
        await apiGetShufflingEdit({ configCarouselId, configCarouselFilez: str, configCarouselSite: '9', configSiteType: '5', configCarouselType: '0', configCarouselTitle: '底部背景图', configCarouselSort: '1' })

      }
    }
  }
  render() {
    const { loading, dataSource, cardSwitch, backgroundSwitch, activeDataSource, topbg, middlebg, bottombg, cardDataSource, cardSource, columnsActive, columnsCarouse, category, dialogStatus, title, btnLoading, initialValues, type, total, activetotal, Cardtotal, cardloading } = this.state
    const { pageNo, pageSize, } = this.state.pageParams
    const { pageActiveNo, pageActiveSize, } = this.state.pageActive
    const { pageCardNo, pageCardSize, } = this.state.pageCard
    return <div className={"p-layout-box configuration"}>
      <div>
        <div className={"p-layout-header shufflingDiv"} >
          <h2>Banner轮播图</h2>
          <TheButton type={'default'} size={'middle'} auth={'shuffling:add'}
            onClick={() => { this.openDialog('add', 'carousel') }} haspermi={['set:shuffling:carouseAdd']}>新增</TheButton>
        </div>
        <div className={"p-layout-content-pagination"}>
          <TheTable loading={loading} dataSource={dataSource} columns={columnsCarouse} />
          <ThePagination pageNo={pageNo} pageSize={pageSize} total={total} pageChange={this.pageChange} />
        </div>

      </div>
      <div style={{ marginTop: '100px' }}>
        <div className={"p-layout-header shufflingDiv"} >
          <h2>横通广告位</h2>
          <TheButton type={'default'} size={'middle'} haspermi={['set:shuffling:activeAdd']}
            onClick={() => { this.openDialog('add', 'active') }}>新增</TheButton>
        </div>
        <div className={"p-layout-content-pagination"}>
          <TheTable loading={loading} dataSource={activeDataSource} columns={columnsCarouse} />
          <ThePagination pageNo={pageActiveNo} pageSize={pageActiveSize} total={activetotal}
            pageChange={this.pageActiveChange}
          />
        </div>
      </div>
      <div style={{ marginTop: '100px' }}>
        <div className={"p-layout-header shufflingDiv"}>
          <Space>
            <h2>卡片轮播图</h2>
            <div style={{ color: '#bbb', fontSize: '13px' }}>
              <Switch checked={cardSwitch} onClick={this.bannerOnChange} />
              &nbsp;&nbsp;开启显示后卡片广告位会同时显示！
            </div>
          </Space>

          <TheButton type={'default'} size={'middle'} haspermi={['set:shuffling:activeAdd']}
            onClick={() => { this.openDialog('add', 'card') }}>新增</TheButton>
        </div>
        <div className={"p-layout-content-pagination"}>
          <TheTable loading={cardloading} dataSource={cardDataSource} columns={columnsCarouse} />
          <ThePagination pageNo={pageCardNo} pageSize={pageCardSize} total={Cardtotal}
            pageChange={this.pageCardChange}
          />
        </div>
      </div>
      <div style={{ marginTop: '100px' }}>
        <div className={"p-layout-header shufflingDiv"} >
          <h2>卡片广告位</h2>
          {cardSource.length < 2 ? <TheButton type={'default'} size={'middle'} haspermi={['set:shuffling:activeAdd']}
            onClick={() => { this.openDialog('add', 'cardCross') }}>新增</TheButton> : null}
        </div>
        <div className={"p-layout-content-pagination"}>
          <TheTable loading={loading} dataSource={cardSource} columns={columnsActive} />
        </div>
      </div>
      <div style={{ marginTop: '40px' }}>
        <div className={"p-layout-header shufflingDiv"} >
          <Space>
            <h2>背景氛围图</h2>
            <div style={{ color: '#bbb', fontSize: '13px' }}>
              <Switch checked={backgroundSwitch} onChange={this.backGroundOnSwitch} />
              &nbsp;&nbsp;开启后会显示在首页！
            </div>
          </Space>
        </div>
        <div className={"p-layout-content-pagination"}>
          <div>
            顶部背景图片
            <TheUpload isConversion={false} maxSize={10} fileList={topbg} data={{ attachKey: '1' }} len={1} getFileResult={this.getTopFileResult} />
          </div>
          <div>
            中部背景图片
            <TheUpload isConversion={false} maxSize={10} fileList={middlebg} data={{ attachKey: '1' }} len={1} getFileResult={this.getMiddleFileResult} />
          </div>
          <div>
            底部背景图片
            <TheUpload isConversion={false} maxSize={10} fileList={bottombg} data={{ attachKey: '1' }} len={1} getFileResult={this.getBottomFileResult} />
          </div>
        </div>
      </div>
      <TheDialog
        visible={dialogStatus}
        title={title}
        width={800}
        handleCancel={this.dialogCancel}
        footer={null}
      >
        <Editor dialogCancel={this.dialogCancel} onFinish={this.onFinish} data={initialValues}
          btnLoading={btnLoading}
          type={type}
          category={category} />
      </TheDialog>
    </div>
  }
}

export default Shuffling